#include "math.h"
#include "stdlib.h"
#include "stdio.h"
#include "string.h"
#include "inc/core/ucgrid1d.h"

#define PARTICLE_IN_CELL 1
#define PARTICLE_OUT_CELL 2

/*utilites*/
void linear_interpolation(floatdig *l_val, floatdig* l_pos,
        floatdig *r_val, floatdig* r_pos,
        floatdig *pos, floatdig* interpolated_val) {
    floatdig k = (*l_val - *r_val) / (*l_pos - *r_pos);
    floatdig b = *l_val - k * (*l_pos);
    *interpolated_val = k * (*pos) + b;
}

int is_particle_in_cell(floatdig pos, floatdig lbound, floatdig rbound) {
    if ((pos < rbound) && (pos > lbound)) {
        return PARTICLE_IN_CELL;
    } else {
        return PARTICLE_OUT_CELL;
    }
}

int get_num_of_particles_in_cell(ucgrid1d* init, particles_set* set, int cell_num);

/*API*/
void ucgrid1d_init_grid(init_ucgrid1d* init, ucgrid1d* grid) {
#ifdef VERBOSE
    printf("init ucgrid1d\n");
#endif
    if ((init != NULL) && (grid != NULL)) {

        floatdig mins;
        floatdig maxs;
        int num_of_cells = 0;
        int i = 0;

        memcpy((void*)&(grid->parameters), (void*)init, sizeof(grid->parameters));
        mins = grid->parameters.min_z;
        maxs = grid->parameters.max_z;
        grid->cellsize = ceil(floatdig(maxs - mins) / (grid->parameters.numofcells));
     }
}

void ucgrid1d_get_cell_center_pos(ucgrid1d* grid, int cell_num, floatdig* pos) {
    //do not use any checks because we want speeed!
    *pos = grid->cellsize * (cell_num + 0.5);
}

int ucgrid1d_search_neighbor_cells(ucgrid1d* grid, floatdig pos, int *left, int *right) {
    //it is supposed the function gets normilized to grid's cell size
    //particles' coordinates

    floatdig a = pos/(grid->cellsize);
    *left = floor(a);
    *right = ceil(a);
    return OK;
}
